package cn.com.pajx.pajx_visitor_v3.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;

import java.util.Locale;
import java.util.Objects;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.mvp.view.IBaseView;
import cn.com.pajx.pajx_visitor_v3.ui.activity.CommonSuccessActivity;
import cn.com.pajx.pajx_visitor_v3.ui.view.dialog.LoadingDialog;
import cn.com.pajx.pajx_visitor_v3.ui.view.statelayout.StateLayoutHelper;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.CommonUtil;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;
import cn.com.pajx.pajx_visitor_v3.utils.SharePreferencesUtil;
import cn.com.pajx.pajx_visitor_v3.utils.ToastUtil;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public abstract class BaseFragment extends DialogFragment implements IBaseView {

    protected Context mContext;
    private LoadingDialog mLoadingDialog;
    private Unbinder unbinder;
    protected StateLayoutHelper helper;
    private TextToSpeech textToSpeech;

    protected int getStatusBarHeight() {
        int height = 0;
        height = CommonUtil.getStatusBarHeight(requireActivity());
        return height;
    }

    @Override
    public void onStart() {
        super.onStart();
        initScreenParams();
    }

    private void initScreenParams() {
        Dialog dialog = getDialog();
        if (dialog != null) {
            Window window = dialog.getWindow();
            DisplayMetrics dm = new DisplayMetrics();
            requireActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            assert window != null;
            window.setLayout((int) (dm.widthPixels * loadWidthScale()), ViewGroup.LayoutParams.WRAP_CONTENT);
            window.setBackgroundDrawableResource(android.R.color.transparent);
        }
    }

    public String setTag() {
        return null;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        this.mContext = context;
        super.onAttach(context);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        // 设置自定义样式去除黑边
        if (dialog.getWindow() != null) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }
        return dialog;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        unbinder = ButterKnife.bind(this, view);
        initConfig();
        beforeInitHead();
        mLoadingDialog = new LoadingDialog(mContext);
        initView(view, savedInstanceState);
        return view;
    }

    private void initConfig() {
        dynamicHideNavigationBar();
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
    }

    /**
     * 隐藏底部导航栏
     */
    public void dynamicHideNavigationBar() {
        Window window = Objects.requireNonNull(getDialog()).getWindow();
        // 保持布局状态,隐藏底部导航
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |// 隐藏导航栏
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        uiOptions |= 0x00001000;
        assert window != null;
        window.getDecorView().setSystemUiVisibility(uiOptions);
        window.getDecorView().setOnSystemUiVisibilityChangeListener(visibility -> dynamicHideNavigationBar());
        //保持屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    protected abstract void initView(View view, Bundle savedInstanceState);

    protected abstract void beforeInitHead();

    protected abstract int getLayoutId();

    /**
     * 设置StateHelperView
     *
     * @param view 需要替换的View
     */
    protected void setHelperView(View view) {
        helper = new StateLayoutHelper(view);
    }

    /**
     * 设置标题栏标题
     */
    protected double loadWidthScale() {
        return 0.6;
    }

    @Override
    public void showProgress() {
        if (mLoadingDialog != null) {
            mLoadingDialog.show();
        }
    }

    @Override
    public void showProgress(String message) {
        if (mLoadingDialog != null) {
            mLoadingDialog.setMessage(message).show();
        }
    }

    @Override
    public void hideProgress(String tag) {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onSuccess(String data, String aesKey, String message, int code, String tag) {

    }

    @Override
    public void onError(String message, int code, String tag) {
        ToastUtil.toast(message);
    }

    @Override
    public void onFailed(Throwable throwable, String tag) {

    }

    /**
     * 监听返回按钮事件
     */
    private final View.OnClickListener onBackClickListener = v -> onClickBack();

    protected void onClickBack() {
        requireActivity().getSupportFragmentManager().popBackStack();
    }

    @Override
    public void dismiss() {
        super.dismiss();
        EventBus.getDefault().post(new EventMessage(AppConstant.FRAGMENTDIALOG_DISMISS));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
            mLoadingDialog = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    //参数检查
    protected boolean checkNullParam(String... params) {
        for (String param : params) {
            if (param == null) {//此app种有允许传递字符串为"" 的情况，所以用是否为空对象来判断
                ToastUtil.toast("关键参数不能为空");
                return true;
            }
        }
        return false;
    }

    /**
     * 退出程序
     * <p>
     * 令牌过期，
     */
    public void exitToLogin(Context mContext, String message) {
        ToastUtil.toast(message);
        SharePreferencesUtil.getInstance().putBoolean("IS_LOGIN", false);
//        mContext.startActivity(new Intent(mContext, LoginActivity.class));
    }

    /**
     * 关闭软键盘
     */
    protected void hideSoftInput() {
        // 虚拟键盘隐藏 判断view是否为空
        View decorView = getDialog().getWindow().peekDecorView();
        if (decorView != null) {
            // 隐藏虚拟键盘
            InputMethodManager inputManger = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            assert inputManger != null;
            inputManger.hideSoftInputFromWindow(decorView.getWindowToken(), 0);
        }
    }

    /**
     * 中文语音播报
     *
     * @param content 播报的文字
     */
    protected void speckChinese(String content) {
        textToSpeech = new TextToSpeech(mContext, status -> {
            LogUtils.e("status=" + status);
            if (status == TextToSpeech.SUCCESS) {
                int result = textToSpeech.setLanguage(Locale.CHINESE);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    ToastUtil.toast("不支持中文播报");
                } else {
                    textToSpeech.speak(content, TextToSpeech.QUEUE_FLUSH, null);
                }
            } else {
                ToastUtil.toast("未检测到语音引擎");
            }
        });
        //播报进度
        textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
            @Override
            public void onStart(String s) {

            }

            @Override
            public void onDone(String s) {
                if (textToSpeech != null) {
                    textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
                    textToSpeech.shutdown(); // 关闭，释放资源
                }
            }

            @Override
            public void onError(String s) {

            }
        });
    }

    protected void skip2Success(String type) {
        Intent intent = new Intent(mContext, CommonSuccessActivity.class);
        intent.putExtra(AppConstant.TYPE, type);
        startActivity(intent);
        dismiss();
    }

}
